package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"test/common"
	"test/model"
	"time"
)

func ChoooseCourse(ctx *gin.Context) {
	DB := common.GetDB()
	fmt.Println("我是选择课程")
	requestUser := make(map[string]interface{})
	//获取参数
	var scs model.Scs
	var students model.Students
	var courses model.Courses
	ctx.ShouldBind(&requestUser)
	//fmt.Println(requestUser)
	sname := requestUser["Sname"].(string)
	DB.Where("sname = ?",sname).First(&students)
	cno := int(requestUser["Cno"].(float64))
	DB.Where("cno=?",cno).First(&courses)
	fmt.Println(courses.Cno)
	DB.Where("cno = ?",courses.Cno).First(&scs)
	fmt.Println("scs。sno",scs.Sno,"sno",students.Sno)
	if courses.Cneed <= courses.Cjoin {
		ctx.JSON(200,gin.H{
			"code" : 200,
			"msg" : "报名失败",
		})
		return
	}
	if scs.Sno == students.Sno {
		ctx.JSON(200,gin.H{
			"code" : 200,
			"msg" : "已经报名",
		})
		return
	}
	fmt.Println(scs)
	DB.Create(&scs)
	//返回结果
	ctx.JSON(200, gin.H{
		"code" : 200,
		"msg": "报名成功",
	})
}

func CoursePay(ctx *gin.Context)  {
	DB := common.GetDB()
	var paylist model.Paylist
	var courses model.Courses
	var students model.Students
	requestUser := make(map[string]interface{})
	fmt.Println(requestUser,"我是支付")
	fmt.Println(requestUser[""])
	//获取参数
	ctx.ShouldBind(&requestUser)
	sname := requestUser["Sname"].(string)
	DB.Where("sname = ?",sname).First(&students)
	cno,_ := strconv.Atoi(requestUser["Cno"].(string))
	DB.Where("cno = ?",cno).First(&courses)
	paylist.Cno = cno
	paylist.Sno = students.Sno
	paylist.Cpayment = courses.Cpayment
	paylist.Cname = courses.Cname
	fmt.Println(paylist)
	ctx.JSON(http.StatusOK,paylist)
}

func PayResult(ctx *gin.Context) {
	DB := common.GetDB()
	var accounts model.Accounts
	var courses model.Courses
	var students model.Students
	requestUser := make(map[string]interface{})
	fmt.Println(requestUser,"我是支付成功")
	//获取参数
	ctx.ShouldBind(&requestUser)
	fmt.Println(requestUser)
	DB.Last(&accounts)
	sno := int(requestUser["Sno"].(float64))
	fmt.Println("1")
	DB.Where("sno = ?",sno).First(&students)
	cno := int(requestUser["Cno"].(float64))
	fmt.Println("2")
	DB.Where("cno = ?",cno).First(&courses)
	asno := sno
	acno := courses.Cno
	amount := courses.Cpayment
	adate := time.Now().Add(7 * 24 * time.Hour).Format("2006-01-02 15:02:05")
	num,_ := strconv.Atoi(accounts.Aclass_cno)
	fmt.Println(courses.Cjoin,"支付前")
	fmt.Println(courses)

	fmt.Println(courses.Cjoin,"支付后")
	fmt.Println(students.Spayment,"支付前")
	fmt.Println(students)
	courses.Cjoin = courses.Cjoin + 1
	students.Spayment = students.Spayment + amount
	DB.Where("sno = ?",students.Sno).Updates(&students)
	DB.Where("cno",courses.Cno).Updates(&courses)
	fmt.Println(students.Spayment,"支付后")
	alass_cno := string(num+1)
	fmt.Println()
	newAccounts := model.Accounts{
		Aclass_cno: alass_cno,
		Adate: adate,
		Acno: acno,
		Asno: asno,
		Aamount: amount,
	}
	DB.Create(&newAccounts)
	//返回结果
	ctx.JSON(200, gin.H{
		"code" : 200,
		"msg": "支付成功",
	})
}
